var fileUploadURL;
var fileList;
var ft;
var options;
var currentOffset;
var numFiles;
var uploadCompletedCallback;
var failedPaths;
var progressPercent;

function setURL(url)
{
	fileUploadURL=url;
}

function setFileList(files)
{
	fileList=files;
}

function startBatchFileUpload(uploadCompleted)
{
	failedPaths = new Array();
	uploadCompletedCallback=uploadCompleted;
	currentOffset=0;
	ft=new FileTransfer();
	options=new FileUploadOptions();
	options.fileKey="file";//@note: this is for the server side script
	
	numFiles=fileList.length;
	progressPercent=100/numFiles;
	
	if(currentOffset<numFiles)
		uploadFile(fileList[currentOffset]);
}

function uploadFile(filePath)
{
	var params = new Object();
	
    options.fileName=filePath.substr(filePath.lastIndexOf('/')+1);
    options.mimeType="image/jpeg";
    //@todo: put in file exists validation as well - ask peter
    
    ft.upload(filePath, fileUploadURL, uploadBatchSuccess, uploadBatchFailed, options);   
}

function uploadBatchSuccess(r)
{
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
    
    console.log("successfully uploaded: "+fileList[currentOffset]);
    
    checkUploadComplete(failedPaths);
	
}

function uploadBatchFailed(error)
{
	console.log("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
    
    console.log("upload failed: "+fileList[currentOffset]);

	failedPaths.push(fileList[currentOffset]);
	
    checkUploadComplete();
}

function checkUploadComplete()
{
	currentOffset++;
	plus('element1',progressPercent);
    
    if(currentOffset<numFiles)
		uploadFile(fileList[currentOffset]);
	else
	{
		//we're done uploading
		console.log("Files upload completed");
		uploadCompletedCallback(failedPaths);
	}
}